import React, {createContext, useEffect, useState} from 'react'
import {getIsAuth, signInUser} from '../api/auth'
import {useToast} from "@chakra-ui/react";
import {useNavigate} from "react-router-dom";
// import { useNotification } from '../hooks'
export const AuthContext = createContext()
const defaultAuthInfo = {
    profile: null,
    isLoggedIn: false,
    isPending: false, // 登录中
    error: ''
}

const AuthProvider = ({children}) => {
    const toast = useToast()
    const navigator = useNavigate()

    // 用户身份信息
    const [authInfo, setAuthInfo] = useState({...defaultAuthInfo})
    // 登录
    // const handleLogin = async (username, password, isStudent) => {
    const handleLogin = async (username, password, role) => {
        setAuthInfo({...authInfo, isPending: true})
        // const {data, code, msg} = await signInUser({username, password, isStudent})
        const {data, code, msg} = await signInUser({username, password, role})
        console.log(data)
        if (code === 0) {
            toast({
                title: msg,
                status: 'error',
                position: 'top',
                isClosable: true,
            })
            return setAuthInfo({...authInfo, isPending: false, error: msg})
        }
        setAuthInfo({profile: {...data}, isPending: false, isLoggedIn: true, error: ''})
        // 保存jwt
        localStorage.setItem('auth-token', data.token)
        localStorage.setItem('auth-info', JSON.stringify(authInfo))
        toast({
            title: '登录成功',
            status: 'success',
            position: 'top',
            isClosable: true,
        })
        navigator('/')
    }
    // 登出
    const handleLogout = async (email, password) => {
        localStorage.removeItem('auth-token')
        localStorage.removeItem('auth-info')
        setAuthInfo({...defaultAuthInfo})
    }
    // 验证token 注意: 刷新页面后会清空authinfo状态
    const isAuth = async () => {
        const token = localStorage.getItem('auth-token')
        console.log(token)
        if (!token) {
            toast({
                title: `登录过期, 请重新登录`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
            setAuthInfo({...authInfo, isLoggedIn: false, isPending: true})
            localStorage.removeItem('auth-info')
            return
        }
        setAuthInfo({...authInfo, isPending: true})
        const {code, msg, data} = await getIsAuth(token)
        if (code === 0) {
            console.log(1)
            toast({
                title: msg,
                status: 'error',
                position: 'top',
                isClosable: true,
            })
            localStorage.removeItem('auth-info')
            return setAuthInfo({...authInfo, isLoggedIn: false, isPending: false, error: msg})
        }
        setAuthInfo({
            profile: {...data},
            isPending: false, isLoggedIn: true, error: ''
        })
        console.log('is auth')
        console.log(data)
        localStorage.setItem('auth-info', JSON.stringify(data))
    }

    // 初始化时先执行一次权限验证
    useEffect(() => {
        isAuth()
        // (async function () {
        //     await isAuth()
        // })()
    }, [])

    return (
        <AuthContext.Provider
            value={{authInfo, handleLogin, isAuth, handleLogout}}>
            {children}
        </AuthContext.Provider>
    )
}

export default AuthProvider